import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useProductStore = defineStore('product', () => {
    // 状态
    const products = ref<any[]>([])
    const searchQuery = ref('')
    const selectedCategory = ref('')
    const selectedSchool = ref('')
    const loading = ref(false)
    const currentPage = ref(1)
    const totalPages = ref(1)
    const viewHistory = ref<any[]>([])

    // 计算属性
    const filteredProducts = computed(() => {
        let result = [...products.value]

        if (searchQuery.value) {
            result = result.filter(product =>
                product.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                product.description.toLowerCase().includes(searchQuery.value.toLowerCase())
            )
        }

        if (selectedCategory.value) {
            result = result.filter(product => product.category === selectedCategory.value)
        }

        if (selectedSchool.value) {
            result = result.filter(product => product.school === selectedSchool.value)
        }

        return result
    })

    const recommendedProducts = computed(() => {
        // 基于浏览历史和用户喜好的推荐算法
        const recommendations = [...products.value]

        // 按照浏览历史中的分类频率排序
        const categoryFrequency = viewHistory.value.reduce((acc, product) => {
            acc[product.category] = (acc[product.category] || 0) + 1
            return acc
        }, {})

        recommendations.sort((a, b) => {
            const freqA = categoryFrequency[a.category] || 0
            const freqB = categoryFrequency[b.category] || 0
            return freqB - freqA
        })

        return recommendations.slice(0, 10)
    })

    // 方法
    const fetchProducts = async (params = {}) => {
        try {
            loading.value = true
            // TODO: 实现获取商品列表的API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            // 模拟数据
            products.value = Array(20).fill(null).map((_, index) => ({
                id: index + 1,
                name: `商品 ${index + 1}`,
                price: Math.floor(Math.random() * 1000) + 100,
                description: '这是一个示例商品描述...',
                category: ['数码', '图书', '服装', '生活'][Math.floor(Math.random() * 4)],
                school: ['北京大学', '清华大学', '复旦大学', '上海交通大学'][Math.floor(Math.random() * 4)],
                location: {
                    latitude: 39.9 + Math.random() * 0.1,
                    longitude: 116.3 + Math.random() * 0.1
                },
                images: [
                    `https://via.placeholder.com/300x200/409EFF/FFFFFF?text=Product+${index + 1}`
                ],
                seller: {
                    id: Math.floor(Math.random() * 100),
                    name: `卖家 ${Math.floor(Math.random() * 100)}`,
                    rating: 4 + Math.random()
                },
                createdAt: new Date().toISOString(),
                views: Math.floor(Math.random() * 1000),
                favorites: Math.floor(Math.random() * 100)
            }))

            totalPages.value = 5
            return true
        } catch (error) {
            console.error('获取商品列表失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    const getProductById = async (id: number) => {
        try {
            // TODO: 实现获取单个商品详情的API调用
            const product = products.value.find(p => p.id === id)
            if (product) {
                // 添加到浏览历史
                const historyIndex = viewHistory.value.findIndex(p => p.id === id)
                if (historyIndex > -1) {
                    viewHistory.value.splice(historyIndex, 1)
                }
                viewHistory.value.unshift(product)
                // 限制历史记录数量
                if (viewHistory.value.length > 50) {
                    viewHistory.value.pop()
                }
            }
            return product
        } catch (error) {
            console.error('获取商品详情失败:', error)
            return null
        }
    }

    const getSuggestedPrice = async (params: any) => {
        try {
            // TODO: 实现获取价格建议的API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            // 模拟价格建议算法
            const { category, condition } = params
            const similarProducts = products.value.filter(p =>
                p.category === category && Math.abs(p.condition - condition) <= 1
            )

            if (similarProducts.length === 0) return null

            const prices = similarProducts.map(p => p.price)
            const avgPrice = prices.reduce((a, b) => a + b, 0) / prices.length
            const minPrice = Math.min(...prices)
            const maxPrice = Math.max(...prices)

            return {
                suggested: Math.round(avgPrice),
                range: {
                    min: Math.round(minPrice),
                    max: Math.round(maxPrice)
                },
                similar: similarProducts.length
            }
        } catch (error) {
            console.error('获取价格建议失败:', error)
            return null
        }
    }

    return {
        // 状态
        products,
        searchQuery,
        selectedCategory,
        selectedSchool,
        loading,
        currentPage,
        totalPages,
        viewHistory,

        // 计算属性
        filteredProducts,
        recommendedProducts,

        // 方法
        fetchProducts,
        getProductById,
        getSuggestedPrice
    }
}) 